#include "widget.h"
#include <UdpListenerThread.h>
#include <ImagePlayerThread.h>
#include "ui_widget.h"
#include <alibabacloud/oss/OssClient.h>
#include <QCoreApplication>
#include <QFile>
#include <QDebug>
#include <fstream>
#include <QPixmap>
#include <QUdpSocket>
#include <QNetworkInterface>
#include <QThread>
#include <QTimer>
#include <QDir>
#include <QFileInfo>
#include <QPushButton>

using namespace AlibabaCloud::OSS;

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
    , imagePlayer(nullptr)
    , udpListener(nullptr)
{
    ui->setupUi(this);

    // 设置窗口标题
    setWindowTitle("Client 1 - OSS图片播放器");

    // 创建下载按钮
    oss_download = new QPushButton("下载图片", this);
    oss_download->setGeometry(20, 20, 120, 40);
    connect(oss_download, &QPushButton::clicked, this, &Widget::downloadFileFromOSS);

    // 创建图片显示区域
    pic_show = new QLabel(this);
    pic_show->setGeometry(400, 20, 400, 320);
    pic_show->setStyleSheet("border: 2px solid gray; background-color: black;");
    pic_show->setAlignment(Qt::AlignCenter);

    // 创建状态标签
    statusLabel = new QLabel("状态: 就绪", this);
    statusLabel->setGeometry(20, 70, 200, 40);

    // 创建命令显示标签
    commandLabel = new QLabel("最后命令: 无", this);
    commandLabel->setGeometry(20, 120, 120, 40);

    // 初始化图片播放线程
    imagePlayer = new ImagePlayerThread(pic_show, this);
    connect(imagePlayer, &ImagePlayerThread::imageChanged, this, [this](const QString& path) {
        statusLabel->setText("正在播放: " + QFileInfo(path).fileName());
    });

    // 初始化UDP监听线程
    udpListener = new UdpListenerThread(12345, this);
    connect(udpListener, &UdpListenerThread::commandReceived, this, &Widget::handleCommand);
    connect(udpListener, &UdpListenerThread::statusMessage, this, [this](const QString& msg) {
        statusLabel->setText(msg);
    });

    // 启动UDP监听
    udpListener->startListening();

    // 初始化本地图片列表
    localImagePaths << "/home/root/download/oss_download/flower.jpg";
    // 可以添加更多本地图片路径

    // 显示第一张图片
    showFirstImage();
}

Widget::~Widget()
{
    if (imagePlayer) {
        imagePlayer->stopPlayback();
        imagePlayer->deleteLater();
    }

    if (udpListener) {
        udpListener->stopListening();
        udpListener->deleteLater();
    }

    delete ui;
}

void Widget::showFirstImage()
{
    if (!localImagePaths.isEmpty() && QFile::exists(localImagePaths.first())) {
        QPixmap pixmap(localImagePaths.first());
        if (!pixmap.isNull()) {
            pixmap = pixmap.scaled(pic_show->size(), Qt::KeepAspectRatio, Qt::SmoothTransformation);
            pic_show->setPixmap(pixmap);
            statusLabel->setText("显示图片: " + QFileInfo(localImagePaths.first()).fileName());
        }
    }
}

void Widget::handleCommand(const QString& command)
{
    commandLabel->setText("最后命令: " + command);

    if (command == "PLAY") {
        // 开始播放图片
        imagePlayer->startPlayback(localImagePaths, 2000); // 2秒切换一次
        statusLabel->setText("开始播放图片");
    }
    else if (command == "STOP") {
        // 停止播放
        imagePlayer->stopPlayback();
        showFirstImage();
        statusLabel->setText("停止播放");
    }
    else if (command == "DOWNLOAD") {
        // 触发下载
        downloadFileFromOSS();
    }
    else if (command.startsWith("INTERVAL:")) {
        // 设置播放间隔，例如: INTERVAL:1000
        QStringList parts = command.split(":");
        if (parts.size() == 2) {
            bool ok;
            int interval = parts[1].toInt(&ok);
            if (ok && interval > 0) {
                imagePlayer->stopPlayback();
                imagePlayer->startPlayback(localImagePaths, interval);
                statusLabel->setText("设置播放间隔: " + QString::number(interval) + "ms");
            }
        }
    }
    else if (command == "STATUS") {
        // 回复状态信息
        sendStatusResponse();
    }
}

void Widget::sendStatusResponse()
{
    QUdpSocket udpSocket;
    QString status = QString("CLIENT1_STATUS:READY,IMAGES:%1")
                   .arg(localImagePaths.size());

    // 广播状态信息到同一端口
    udpSocket.writeDatagram(status.toUtf8(), QHostAddress::Broadcast, 12345);
    statusLabel->setText("已发送状态响应");
}

void Widget::downloadFileFromOSS()
{
    statusLabel->setText("开始下载图片...");

    try {
        InitializeSdk();

        ClientConfiguration config;
        OssClient client("oss-cn-chengdu.aliyuncs.com",
                        "LTAI5t6QnDkio5fLkYV1hFw1",
                        "4P5WkJFYa63HeqwGtsaI5gkXf698Ry",
                        config);

        // 确保下载目录存在
        QDir dir("/home/root/download/oss_download");
        if (!dir.exists()) {
            dir.mkpath(".");
        }

        GetObjectRequest request("smart-advertising-chengdu-a1b2c3", "flower.jpg");
        request.setResponseStreamFactory([=]() {
            return std::make_shared<std::fstream>(
                "/home/root/download/oss_download/flower.jpg",
                std::ios_base::out | std::ios_base::binary | std::ios_base::trunc
            );
        });

        auto outcome = client.GetObject(request);

        if (outcome.isSuccess()) {
            statusLabel->setText("下载成功");
            // 更新图片显示
            showFirstImage();
            // 添加到播放列表
            if (!localImagePaths.contains("/home/root/download/oss_download/flower.jpg")) {
                localImagePaths << "/home/root/download/oss_download/flower.jpg";
            }
        } else {
            statusLabel->setText("下载失败");
            qDebug() << "下载失败:" << outcome.error().Code().c_str()
                     << outcome.error().Message().c_str();
        }

        ShutdownSdk();

    } catch (const std::exception& e) {
        statusLabel->setText("下载异常: " + QString(e.what()));
        qDebug() << "异常:" << e.what();
    }
}

// 需要在widget.h中添加相应的头文件包含和类声明
